<template>

  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="tableConfig.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.close"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1100px">

    <el-form ref="formMovies" :rules="rulesMovies" :model="formMovies" label-width="180px">
      <el-form-item label="名称" prop="name" >
        <el-input v-model.trim="formMovies.name"></el-input>
      </el-form-item>
      <el-form-item label="导演" prop="director" >
        <el-input v-model.trim="formMovies.director"></el-input>
      </el-form-item>
      <el-form-item label="海报图片" >
        <SinglePictureUploadScreenshot ref="moviesIcoImages"></SinglePictureUploadScreenshot>
      </el-form-item>
      <el-form-item label="主演" prop="toStar" >
        <el-input v-model.trim="formMovies.toStar"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="describe" >
        <el-input v-model.trim="formMovies.describe" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="影视类型" prop="typeId">
        <el-select v-model="formMovies.typeId" placeholder="请选择影视类型">
          <el-option
            v-for="item in moviesType"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="评分" prop="grade" >
        <el-rate v-model="formMovies.grade" :texts="texts" show-text></el-rate>
      </el-form-item>
      <el-form-item label="点评" prop="comment" >
        <el-input v-model.trim="formMovies.comment" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="观看进度" prop="speedOfProgress" >
        <el-select v-model="formMovies.speedOfProgress" placeholder="请选择阅读进度">
          <el-option label="观影完成-完整的看完了" :value="9"></el-option>
          <el-option label="计划中-准备看" :value="1"></el-option>
          <el-option label="观影中断-不会继续追" :value="2"></el-option>
          <el-option label="观影暂停-停止观影后续会继续" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上映年份" prop="publicationYear" >
        <el-input v-model.trim="formMovies.publicationYear"></el-input>
      </el-form-item>
      <el-form-item label="观看地址" prop="locale" >
        <el-input v-model.trim="formMovies.locale"></el-input>
      </el-form-item>
      <el-form-item label="是否追更" prop="continueSee" >
        <el-select v-model="formMovies.continueSee" placeholder="请选择是否追更">
          <el-option label="停止观看" :value="1"></el-option>
          <el-option label="追更" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="已看到多少" prop="page" >
        <el-input v-model.trim="formMovies.page"></el-input>
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="toSaveUpd" v-if="defaultValue.saveUpdSelect !== 'select'">{{defaultValue.title}}</el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>

</template>

<script>

  import http from '@/utils/http'
  import {clearInvalid} from "../../utils/utils"
  import SinglePictureUploadScreenshot from '@/components/common/SinglePictureUploadScreenshot.vue';


  export default {
    name: "MoviesSaveUpd",
    components: {
      SinglePictureUploadScreenshot,
    },
    data(){
      return {
        // 表格的默认值
        tableConfig: {
          // 关闭时销毁 Dialog 中的元素
          destroyOnClose: true,
          // 弹出框是否打开
          show: false,
          // 是否显示关闭按钮
          close: true,
          // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
          lockScroll: false,
          appendToBody: true,
        },
        // 默认值，进入页面后的值
        defaultValue: {
          // 弹出框标题
          title: '查看',
          // 保存还是修改or查看,取值有 select | save | upd
          saveUpdSelect: 'select'
        },
        // 评价文字说明
        texts: ['浪费时间', '勉强入口', '普通', '优秀', '经典'],
        // 影视类型
        moviesType: [],
        // 要提交的数据
        formMovies: {
          id: null,
          typeId: null,
          name: null,
          director: null,
          toStar: null,
          icoPath: null,
          describe: null,
          locale: null,
          comment: null,
          continueSee: null,
          speedOfProgress: null,
          page: null,
          grade: null,
        },
        // 校验规则
        rulesMovies: {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          director: [{ required: true, message: '请输入导演名称', trigger: 'blur' }],
          grade: [{ required: true, message: '请选择评分', trigger: 'blur' }],
          typeId: [{ required: true, message: '请选择书籍类型', trigger: 'change' }],
        },
      }
    },
    methods: {
      /**
       * 打开弹出框之前
       * @param value 保存还是修改or查看,取值有 select \ save \ upd
       * @param obj 如果是修改和查看，则是详细数据,需要赋值
       * @param moviesType 影视类型
       */
      openMoviesPage(value, obj, moviesType){
        // 从父组件传入，减少查询
        this.moviesType = moviesType
        this.defaultValue.saveUpdSelect = value
        this.initMovies()

        if (value === 'save'){
          this.defaultValue.title = '新增影视信息'
          this.getMoviesLocale()

        } else if (value === 'upd'){
          this.defaultValue.title = '修改影视信息'
          this.formMovies = JSON.parse(JSON.stringify(obj))

          // 页面加载完成后执行，否则无法获取到dom
          this.$nextTick(() => {
            // if（aa!=null&&aa!=""）
            if (this.formMovies.icoPath){
              // 对书籍封面进行处理，回显
              let poster = {name: this.formMovies.name, url: this.formMovies.icoPath, uid: this.formMovies.id}
              // 先清空，否则可能数据污染
              this.$refs.moviesIcoImages.upload.fileList = []
              this.$refs.moviesIcoImages.upload.fileList.push(poster)
              this.$refs.moviesIcoImages.uploadHide()
            }
          })

        } else {
          this.defaultValue.title = '影视详情'
          this.formMovies = obj
        }

        this.tableConfig.show = true
        this.$store.commit('navigationListChange', ['影视', this.defaultValue.title])

      },
      /**
       * 是保存还是修改
       */
      toSaveUpd(){
        if (this.defaultValue.saveUpdSelect === 'save'){
          this.saveMovies()

        } else if (this.defaultValue.saveUpdSelect === 'upd'){
          this.updMovies()
        } else {

        }
      },
      /**
       * 更新影视信息
       */
      updMovies(){
        let formData = new FormData()
        clearInvalid(this.formMovies)
        this.appendPram(formData)
        // 处理图片
        let uploadList = this.$refs.moviesIcoImages.upload.fileList
        uploadList.forEach((file) => {
          // 更新的时候，如果没有图片不做处理，这个时候的图片是自己放进去的，但没有 file.raw 数据
          if (file.raw){
            formData.append('file', file.raw)
          }
        });

        http.postFileForm("/movies/updMovies", formData).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.$message.success("更新成功");
          this.$emit('getMoviesPage', null)
          // 关闭弹出框
          this.initMovies()
          this.tableConfig.show = false

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 保存影视信息
       */
      saveMovies(){
        let formData = new FormData()
        this.appendPram(formData)
        // 获取上传的图片
        let uploadList = this.$refs.moviesIcoImages.upload.fileList
        uploadList.forEach((file) => {
          // console.log("ccc", file)
          // console.log("eee", file.raw)
          formData.append('file', file.raw)
        });

        http.postFileForm("/movies/saveMovies", formData).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.$message.success("保存成功");
          this.$emit('getMoviesPage', null)
          // 关闭弹出框
          this.initMovies()
          this.tableConfig.show = false

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 拼接参数
       * @formData 提交的数据
       */
      appendPram(formData){
        for (let key in this.formMovies){
          if (this.formMovies[key]){
            formData.append(key, this.formMovies[key])
          }
        }
      },
      /**
       * 初始化影视参数
       */
      initMovies(){
        this.formMovies = {
          id: null,
          typeId: null,
          name: null,
          director: null,
          toStar: null,
          icoPath: null,
          describe: null,
          locale: null,
          comment: null,
          continueSee: null,
          speedOfProgress: null,
          page: null,
          grade: null,
        }
      },
      /**
       * 获取默认的观影地址
       */
      getMoviesLocale(){
        http.get("/movies/getMoviesLocale", {
        }).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          this.formMovies.locale = res.data.value

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
    }
  }
</script>

<style scoped>

</style>
